﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Web;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Drawing.Imaging;
using Microsoft.SharePoint;
using System.Linq;
using uk.ac.soton.ses.DAL;

namespace uk.ac.soton.ses.layouts
{
    public class BasicImageHandler : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string experimentdatafileidString = context.Request.QueryString["experimentdatafileid"];
            string fileFormatString = context.Request.QueryString["fileformat"];
            if (string.IsNullOrEmpty(fileFormatString))
            {
                fileFormatString = "png";
            }

            int experimentdatafileid = -1; //Database record to use containing the image
            string fileName = ""; //Image name to return (loaded from database)
            Image img = null; //Image to return

            //Error checking: Ensure return type is correct
            if (
                    !int.TryParse(experimentdatafileidString, out experimentdatafileid)
                || !new string[] { "jpg", "jpeg", "png" }.Contains(fileFormatString, StringComparer.OrdinalIgnoreCase)
               )
            {
                context.Response.StatusCode = 400;
                return;
            }

            MaterialsMetadataContext dbcontext = HttpContext.Current.GetMaterialsDBContext();

            try
            {
                //Get the requested data file
                ExperimentDataFile datafile = dbcontext.GetExperimentDataFileByID(experimentdatafileid);

                //Error checking: check the requested file exists in the database
                if (datafile == null)
                {
                    context.Response.StatusCode = 400;
                    return;
                }
                
                fileName = datafile.GetFullPath();

                //Error checking: check the requested file exists on disk
                if (!File.Exists(fileName))
                {
                    context.Response.StatusCode = 400;
                    return;
                }

                //Create the Image object
                //img = Image.FromFile(fileName);
                //There are problems using Image.FromFile (file handle not always released, even after calling Dispose) as discussed here:
                //http://stackoverflow.com/questions/788335/why-does-image-fromfile-keep-a-file-handle-open-sometimes
                //Using a memory stream instead
                using (MemoryStream imageStream = new MemoryStream(File.ReadAllBytes(fileName)))
                {
                    img = Image.FromStream(imageStream);
                }

                switch (fileFormatString)
                {
                    case "jpeg":
                    case "jpg":
                        context.Response.ContentType = "image/jpeg";
                        img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                        break;
                    case "png":
                        context.Response.ContentType = "image/png";
                        //Because Internet Explorer does not support Format32bppArgb, we have to convert it to Format24bppRgb
                        //Clone doesn't work very reliably according to: http://stackoverflow.com/questions/2016406/converting-bitmap-pixelformats-in-c-sharp
                        //  img = ((Bitmap)img).Clone(new Rectangle(0, 0, img.Width, img.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                        //  img.Save(context.Response.OutputStream, ImageFormat.Png);
                        //Therefore, using this method:
                        using (Bitmap bmp24bpp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                        using (Graphics gr = Graphics.FromImage(bmp24bpp))
                        {
                            gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
                            bmp24bpp.Save(context.Response.OutputStream, ImageFormat.Png);
                        }
                        break;
                    default:
                        context.Response.StatusCode = 400;
                        return;
                }
            }
            catch
            {
                context.Response.StatusCode = 400;
                return;
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }

                if (dbcontext != null)
                {
                    dbcontext.Dispose();
                }
            }
        }
        #endregion
    }
}
